import datetime

from sqlalchemy import Row


def success_response(data=None, message="success", code=200):
    """
    成功返回的格式
    :param data: 返回的实际数据
    :param message: 提示信息
    :param code: 自定义状态码，默认为 200
    """
    return {
        "status": "success",
        "code": code,
        "message": message,
        "data": data
    }


def error_response(message="error", code=400, data=None):
    """
    错误返回的格式
    :param message: 错误信息
    :param code: HTTP 状态码，默认为 400
    :param data: 附加数据（可选）
    """
    return {
        "status": "error",
        "code": code,
        "message": message,
        "data": data
    }


def build_dict(columns, result):
    """
    将 sqlalchemy 返回的数据转成包含多个字典的列表，其中每个字典对应数据库的一行数据
    """
    if result is None:
        return None
    columns = list(map(str, columns))
    if isinstance(result, Row):
        return dict(zip(columns, result))
    return [dict(zip(columns, r)) for r in result]


def build_dict_handle_dt(columns, result):
    if result is None:
        return None
    columns = list(map(str, columns))
    if isinstance(result, Row):
        one_row = []
        for each_one in result:
            if isinstance(each_one, datetime.datetime):
                one_row.append(each_one.strftime('%Y-%m-%d %H:%M:%S.%f')[:-3])
            else:
                one_row.append(each_one)
        return dict(zip(columns, one_row))
    else:
        result_dict = []
        for r in result:
            _r = []
            for each_one in r:
                if isinstance(each_one, datetime.datetime):
                    _r.append(each_one.strftime('%Y-%m-%d %H:%M:%S.%f')[:-3])
                else:
                    _r.append(each_one)
            result_dict.append(dict(zip(columns, _r)))
        return result_dict

